package cn.wolfcode.java39.rocketmqconsumerdemo.api._02_producer_type;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AyncProducer {
    public static void main(String[] args) throws Exception {
        //创建一个生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("wolfcode-producer");
        //设置nameserver地址
        producer.setNamesrvAddr("192.168.136.128:9876;192.168.136.129:9876");
        //启动生产者
        producer.start();
        CountDownLatch count = new CountDownLatch(100);
        //创建100个message对象
        for (int i=0; i < 100; i++){
            Message message = new Message("02-producer_type", "hello,rocketmq".getBytes("utf-8"));
            //使用同步的方式发送
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功");
                    //计数器-1
                    count.countDown();
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                    //计数器-1
                    count.countDown();
                }
            });

        }
        //TimeUnit.SECONDS.sleep(5);
        //让线程阻塞,当所有的回掉执行完成之后,才去执行下面的代码
        count.await();//等待计数器的值变为0
        //关闭生产者
        producer.shutdown();
        //需要收到所有的异步回掉信息才关闭

    }
}
